package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) request1;
        HttpServletResponse response = (HttpServletResponse) response1;
        HttpSession session = request.getSession();

        String requestURI = request.getRequestURI();
        log.info("我开始拦截了:{}",requestURI);

        String[] uris = {
                "/front/**",
                "/backend/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean check = check(uris,requestURI);
        if (check){
            log.info("放行路径{}",requestURI);
            chain.doFilter(request, response);
            return;
        }
        Object empId = session.getAttribute("empId");
        if (empId != null){

            log.info("线程id={}",Thread.currentThread().getId());
            log.info("已登录放行{}",requestURI);

            BaseContext.setCurrentId((Long) empId);

            chain.doFilter(request, response);
            return;
        }
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            chain.doFilter(request,response);
            return;
        }

    }

    public boolean check(String[] uris,String requestURI){
        AntPathMatcher matcher =new AntPathMatcher();
        for (String uri : uris) {
            boolean match = matcher.match(uri, requestURI);
            if (match){
                return true;
            }

        }

        return false;
    }
}
